package cn.edu.seig.textbook.controller;


import cn.edu.seig.textbook.domain.dto.TotalOrders;
import cn.edu.seig.textbook.enums.OrderEnum;
import cn.edu.seig.textbook.service.IOrdersService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author day
 * @since 2024-11-07
 */
@Controller
@RequestMapping("/purchase")
public class PurchasesController {
    @Autowired
    private IOrdersService ordersService;

    @RequestMapping("/toPurchase")
    public String toPurchases(Model model,@AuthenticationPrincipal UserDetails userDetails, HttpSession session) {
        session.setAttribute("userDetails", userDetails);
        return "purchase/purchase";
    }
    @RequestMapping("/downloader")
    public String download(){
        return "purchase/downloadReport";
    }
    @RequestMapping("/order_All")
    public String order_All(Model model) {
        List<TotalOrders> totalOrders=ordersService.getTotalOrders();
        model.addAttribute("totalOrders", totalOrders);

        return "purchase/showAllPurchase";
    }
    @RequestMapping("/setOrderStatus")
    public String setOrderStatus() {
        ordersService.setOrderStatus(OrderEnum.ONORDER);
        return "redirect:/purchase/order_All";
    }

    @PostMapping("/totalOrders_Add")
    public String saveTotalOrdersAsCSV(Model model) {
        // 获取 totalOrders 数据
        List<TotalOrders> totalOrders=ordersService.getTotalOrders();

        // 指定保存文件的路径
        String filePath = "src/main/resources/static/purchase_table/total_orders.csv";
        // 修改为实际路径
        File file = new File(filePath);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            // 写入 CSV 文件的标题行
            writer.write("教材ID,教材名,作者,ISBN,价格,出版日期,版本,采购数量,总价格");
            writer.newLine();

            // 写入每个 totalOrder 的数据
            for (TotalOrders totalOrder : totalOrders) {
                writer.write(totalOrder.getTextbookId() + "," +
                        totalOrder.getTextbookName() + "," +
                        totalOrder.getAuthor() + "," +
                        totalOrder.getIsbn() + "," +
                        totalOrder.getPrice() + "," +
                        totalOrder.getPublishDate() + "," +
                        totalOrder.getVersion() + "," +
                        totalOrder.getPurchaseQuantity() + "," +
                        totalOrder.getTotalPrice());
                writer.newLine();
            }

        } catch (IOException e) {

            e.printStackTrace();
            model.addAttribute("error", "保存文件失败：" + e.getMessage());

            return "purchase/successPage";
            // 返回错误页面
        }

        model.addAttribute("message", "CSV 文件保存成功！");
        return "purchase/successPage";
        // 返回成功页面
    }
    @RequestMapping("download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam("filename") String filename) throws Exception{
        // 指定要下载的文件所在路径
        String path = "src/main/resources/static/purchase_table";
        // 创建该文件对象
        File file = new File(path+File.separator+filename);
        // 对文件名编码，防止中文文件乱码
        filename = this.getFilename(request, filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }

    public String getFilename(HttpServletRequest request, String filename) throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示
                return URLEncoder.encode(filename, StandardCharsets.UTF_8);
            }
        }
        //火狐等其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
    }
}
